package com.houdoudou.customer.find;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Machine;
import com.houdoudou.customer.ChooseMachineActivity;
import com.houdoudou.customer.CustomerMainActivity;
import com.houdoudou.customer.FrgBuyOfActMain;
import com.houdoudou.customer.R;
import com.houdoudou.customer.WelcomeAct;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.sqlite.CarManagement;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewDebug.FlagToString;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class SearchMachineActivity extends Activity {
    
	ImageButton search, back;
	ProgressBar progres;
	ListView listview_machine;
	MyListAdapter myListAdapter;
	EditText search_content;
	View.OnClickListener myOnclickListener;
	JSONArray machinesJA= new JSONArray();
	
	int functionCode=9;
	 double longitude=360;	
	 double latitude=360;
	 String LOG="alessio";
	 JSONObject machineJO;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
	  super.onCreate(savedInstanceState);
		setContentView(R.layout.act_search_machine);
		init_listener();
		init_component();
		progres.setVisibility(View.VISIBLE);
		listview_machine.setVisibility(View.GONE);
		
      //  LocationManager locationManager=(LocationManager) SearchMachineActivity.this.getSystemService(Context.LOCATION_SERVICE);
		//  locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new MyLocationListener()); 
		search.performClick();
       	
	}
	private void init_listener(){
		
		
	/////////////////////////////////////////////////////////////////
		
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(v==search){
				 
					   LocationManager locationManager=(LocationManager) SearchMachineActivity.this.getSystemService(Context.LOCATION_SERVICE);
		      		   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new MyLocationListener());
		      		   
					   String[] params= new String[3];
				        params[0]=Constant.BaseUrl+Constant.CustomerUrl;
				        params[1]="searchMachine"; //PostCode
				        machineJO= new JSONObject();  
				     if(!search_content.getText().toString().isEmpty()){      	
				    	 int machineID=0;
				    	 try{ machineID=Integer.parseInt(search_content.getText().toString());	  }catch(Exception e){}
				    	 if(machineID==0){	  machineJO.put(Machine.SEARCH,search_content.getText().toString());
				    	 }else{ machineJO.put(Machine.ID, machineID );}
				    	 }
			         new HttpPostTaskforSearchMachine().execute(params);				 
				    search.setClickable(false);
					search_content.setClickable(false);
				    progres.setVisibility(View.VISIBLE);
					listview_machine.setVisibility(View.GONE);
					
				  }	
			                   
				
				if(v==back){
					SearchMachineActivity.this.finish();
			      }
			               }// onClick			
		                      };		
		      
		
	}
	
	
	private void init_component(){
		
		
		search= (ImageButton) findViewById(R.id.btn_search_act_search_mchn);
		back=(ImageButton) findViewById(R.id.back_act_search_mchn);
		progres= (ProgressBar)findViewById(R.id.prgs_search_act_search_mchn);
		listview_machine= (ListView) findViewById(R.id.list_act_search_mchn);
		search_content= (EditText) findViewById(R.id.et_search_act_search_mchn);
		//////////////////////
		
		search.setOnClickListener(myOnclickListener);
	    back.setOnClickListener(myOnclickListener);
		
	  
		myListAdapter= new MyListAdapter(this);
		listview_machine.setAdapter(myListAdapter);
		listview_machine.setOnItemClickListener(new AdapterView.OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				  final View cview=view;
				  final long cid=id;
				  final int cposition=position;
				 
				  final int Machine_ID_New=machinesJA.getJSONObject(position).getInt(Machine.ID);
				 
				  //如果当前，没有配置机器，直接处理
				  if(Constant.machineJO==null||Constant.machineJO.getInt(Machine.ID)==Machine_ID_New){								 			
				  Constant.machineJO=machinesJA.getJSONObject(cposition);
				  SharedPreferences sharedPreferences = SearchMachineActivity.this.getSharedPreferences("config", Context.MODE_PRIVATE);
				  Editor editor = sharedPreferences.edit();   
				  editor.putString("machine", Constant.machineJO.toString());				 
				  editor.commit();			  
				  FrgBuyOfActMain.needPullSupplier=true;
				  FrgBuyOfActMain.PullSuccess=false;
				  System.out.println("search-------SELECTED------machine="+Constant.machineJO.toString());
				  Intent intent= new Intent(SearchMachineActivity.this, CustomerMainActivity.class); 
				   intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				     startActivity(intent);
				SearchMachineActivity.this.finish();
				 
				// 配置了机器的，更换机器，要清空购物车。 
				  }else{
					           Builder b = new AlertDialog.Builder(SearchMachineActivity.this).setTitle("更换自提柜提醒")  
							           .setMessage("更换自提柜，将清空购物车，更换？");  
							   b.setPositiveButton("继续", new DialogInterface.OnClickListener() {  
							    public void onClick(DialogInterface dialog, int whichButton) {  
							    	 Constant.machineJO=machinesJA.getJSONObject(cposition);
							    	 new CarManagement(SearchMachineActivity.this).deleteAll();
							    	 Constant.showWelcome=false;
							    	  listview_machine.performItemClick(cview, cposition, cid);
							    	 
							    }  
							   })
							   .setNegativeButton("取消",new DialogInterface.OnClickListener() {  
								    public void onClick(DialogInterface dialog, int whichButton) {  
									     dialog.cancel();  
									   
									    }  
							   }).show();  
					  
				  }			  
			}
			
		});
		
		
	}
	
	
	
	
	
	private  class HttpPostTaskforSearchMachine extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();
			  while(longitude==360||latitude==360){
				  ;
			  }
			  JSONObject jsonData=new JSONObject();
			  JSONObject location= new JSONObject();
			  location.put("longitude", longitude);
			  location.put("latitude", latitude);
			  jsonData.put("location", location);
		      jsonData.put("machine", machineJO);
	          params[2]=jsonData.toString();
			
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
			// TODO Auto-generated method stub
		  //	super.onPostExecute(result);
		//	confirm.setEnabled(true);
		//	result.setText("");
			 search.setClickable(true);
			 search_content.setClickable(true);
			 progres.setVisibility(View.GONE);
			 listview_machine.setVisibility(View.VISIBLE);
			 longitude=360;
			 latitude=360;
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
		   //   result.setText("提示:网络故障或者网络配置有误，无法连接到服务器");
				 CommonFunction.alert(SearchMachineActivity.this, "错误", "网络故障");
		      return; }
			
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean ActionStatus=false;
				String ErrorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 ActionStatus=json.getBoolean("success");
				 ErrorInfo=json.getString("errorInfo");	
				}catch(JSONException e){			
					CommonFunction.alert(SearchMachineActivity.this, "错误", "JSON解析错误"); return;
				}
										   												      		       
		       if(ActionStatus){     
		    	   machinesJA= json.getJSONArray("machines");		
					 myListAdapter.notifyDataSetChanged(); 
		             } // ifActionStatus			
		  
		
		} //onPostExecute
 } //AsyncTask
	
	class MyListAdapter extends BaseAdapter {
		   
		
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public MyListAdapter(Context context) {
				super();
				
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public TextView zj_address,zj_name,zj_id,zj_distance;  
	       
	        public ImageView machine_pic;
	      
	    
	   }   //end of Zujian

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return machinesJA.size();  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return machinesJA.get(position);  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	 
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
		//	final int selectID = position;   
			 Zujian zujian=null;  
		        if(convertView==null){  
		            zujian=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_act_search_mchn, null);  
		          
		            zujian.zj_id=(TextView) convertView.findViewById(R.id.no_list_act_search_mchn);
		            zujian.zj_name=(TextView) convertView.findViewById(R.id.name_list_act_search_mchn); 
		            zujian.zj_address=(TextView) convertView.findViewById(R.id.address_list_act_search_mchn); 
		            zujian.zj_distance= (TextView) convertView.findViewById(R.id.distance_list_act_search_mchn);
		            zujian.machine_pic=(ImageView) convertView.findViewById(R.id.img_list_act_search_mchn);     
		                 
		            convertView.setTag(zujian);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zujian=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		        zujian.zj_id.setText( machinesJA.getJSONObject(position).getInt(Machine.ID)+"");
		        zujian.zj_address.setText( machinesJA.getJSONObject(position).getString(Machine.ADDRESS));
		        zujian.zj_name.setText( machinesJA.getJSONObject(position).getString(Machine.NAME));
		        int distance= (int) machinesJA.getJSONObject(position).getDouble("distance");
		        String distanceWord; 
		        if(distance/1000>0){distanceWord="距离约"+distance/1000+"千 "+distance%1000+"米";
		        }else{distanceWord="距离约"+distance+"米"; }
		        zujian.zj_distance.setText(distanceWord);  
		        
		        
		        return convertView;
	           } 
	      }// end Adapter
	
	
	
	
	class  MyLocationListener implements LocationListener{

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			Log.d(LOG, "Longitude---->"+location.getLongitude());
			Log.d(LOG, "Latitude---->"+location.getLatitude());
			System.out.println("Longitude---->"+location.getLongitude());
			System.out.println("Latitude---->"+location.getLatitude());
			latitude=location.getLatitude();
			longitude=location.getLongitude();
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}		
	 }
	
	private void toast(String message){
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
	}
}
